package org.apache.rocketmq.common.utils;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;


/**
 * @课程描述:从零带你写框架系列中的课程，整个系列包含netty，xxl-job，rocketmq，nacos，sofajraft，spring，springboot，disruptor，编译器，虚拟机等等。
 * @author：陈清风扬，个人微信号：chenqingfengyangjj。
 * @date:2024/12/31
 * @方法描述：启动关闭管理器的抽象父类，所有启动关闭管理器都会添加到这个类的startAndShutdownList集合中
 */
public abstract class AbstractStartAndShutdown implements StartAndShutdown {

    //存放启动关闭管理器的集合
    protected List<StartAndShutdown> startAndShutdownList = new CopyOnWriteArrayList<>();


    //添加启动关闭管理器的方法
    protected void appendStartAndShutdown(StartAndShutdown startAndShutdown) {
        this.startAndShutdownList.add(startAndShutdown);
    }

    //启动proxy模块中所有StartAndShutdown对象的方法
    @Override
    public void start() throws Exception {
        for (StartAndShutdown startAndShutdown : startAndShutdownList) {
            startAndShutdown.start();
        }
    }

    //关闭proxy模块中所有StartAndShutdown对象的方法
    @Override
    public void shutdown() throws Exception {
        int index = startAndShutdownList.size() - 1;
        for (; index >= 0; index--) {
            startAndShutdownList.get(index).shutdown();
        }
    }

    //关闭所有StartAndShutdown对象前的预处理操作
    @Override
    public void preShutdown() throws Exception {
        int index = startAndShutdownList.size() - 1;
        for (; index >= 0; index--) {
            startAndShutdownList.get(index).preShutdown();
        }
    }


    public void appendStart(Start start) {
        this.appendStartAndShutdown(new StartAndShutdown() {
            @Override
            public void shutdown() throws Exception {

            }

            @Override
            public void start() throws Exception {
                start.start();
            }
        });
    }

    public void appendShutdown(Shutdown shutdown) {
        this.appendStartAndShutdown(new StartAndShutdown() {
            @Override
            public void shutdown() throws Exception {
                shutdown.shutdown();
            }

            @Override
            public void start() throws Exception {

            }
        });
    }
}
